package test;


import java.net.*;
import java.util.*;
 
public class Server2
{
	public static Map<String,String> map=new HashMap<String,String>();
	public static void main(String args[]) throws Exception
	{
		
		int clientPort=0;
		String ip="";
		DatagramSocket ds= new DatagramSocket(1234);
		String message="";
		String str="";
		byte by[]=new byte[2000];
		DatagramPacket dp=new DatagramPacket(by,0,by.length);
		SocketAddress socketAddress = null;
		InetSocketAddress inetSocketAddress = null;
		while(true)
		{
			System.out.println("wait...");
			ds.receive(dp);
			System.out.println("success");
			message=new String(dp.getData(),0,dp.getLength());
			System.out.println("message:"+message);
			socketAddress=dp.getSocketAddress();
			dp.getPort();
			inetSocketAddress = (InetSocketAddress) socketAddress;
			clientPort=inetSocketAddress.getPort();
			ip=inetSocketAddress.getAddress().getHostAddress();
			if(message.startsWith("getIp"))
			{
				map.put(String.valueOf(clientPort),ip);
				str=clientPort+","+ip;
				byte buf[]=str.getBytes();
				dp.setData(buf,0,buf.length);
				ds.send(dp);
				System.out.println(clientPort+","+ip);
			}
			if(message.startsWith("aa"))
			{
				Set<String> set=map.keySet();
				Iterator<String> iter=set.iterator();
				while(iter.hasNext())
				{
					String key=iter.next();
					String value=map.get(key);
					System.out.println(key+"clientPort"+clientPort);
					if(clientPort!=Integer.valueOf(key))
					{
						str="udp"+","+key+","+value;
						byte buf[]=str.getBytes();
						dp.setData(buf,0,buf.length);
						ds.send(dp);
						System.out.println("send");
					}
				}
			}
			if(message.startsWith("sendMessage"))
			{
				String port=message.split(",")[1];
				String targetIp=message.split(",")[2];
				str=message.split(",")[3];
				byte buf[]=str.getBytes();
				SocketAddress sa=new InetSocketAddress(targetIp,Integer.valueOf(port));
				DatagramPacket target=new DatagramPacket(buf,0,buf.length,sa);
				ds.send(target);
			}
			dp.setData(by,0,by.length);
		}
	}
}
